package com.tangyee.utils;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.tangyee.home.activity.db.UsersInfo;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author leeguiyang@yeah.net
 * 这是用广播接收器来获取的sessionid这样只要发一个广播就能获取刀sessionid了
 */
public class SessionReceiver extends BroadcastReceiver implements SessionHelper {

    private static final String TAG = "SessionReceiver";
    private String usrBroad;//服务中的用户名
    private String pwdBroad;//服务中的密码
    private String phoneBroad;//手机号码
    private Context context;

    //由于这是发射器所以不处理，不接受自己发射广播
    @Override
    public final void registerSessionReceiver() {
    }

    @Override
    public final void unregisterSessionReceiver() {
    }

    @Override
    public void onReceive(Context contxt, Intent intent) {
        context = contxt;
        localHandle(contxt, intent);
        Log.d(TAG, "接收到了广播" + intent.getAction());
    }

    private void localHandle(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (null != info && info.isConnected()) {
            String action = intent.getAction();
            Log.d(TAG, "在广播接收器中启动了");
            if (action.equals(I_NEED_SESSIONID_BY_BROAD)) {
                //登录时候的操作
                usrBroad = intent.getStringExtra(USERNAME);
                pwdBroad = intent.getStringExtra(PASSWORD);
                Log.d(TAG, usrBroad);
                Log.d(TAG, pwdBroad);
                //获取后直接启动一个后台线程为其服务
                new SessionTask(context, usrBroad, pwdBroad).execute();
                Log.d(TAG, "启动了一个登录获取的任务By Localhandle");
            } else if (action.equals(I_WANT_REGISTER_BY_BROAD)) {
                //注册
                usrBroad = intent.getStringExtra(USERNAME);
                pwdBroad = intent.getStringExtra(PASSWORD);
                phoneBroad = intent.getStringExtra(PHONENUMBER);
                new SessionTask(context, usrBroad, pwdBroad, phoneBroad).execute();
                Log.d(TAG, "启动一个注册服务");
            }
        } else {
            Toast.makeText(context,"好像没联网哦，联网后试下吧！",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 由于不能再主线程上进行数据联网的操作，所以新建一个进程
     */
    private class SessionTask extends AsyncTask<Void, Void, String> {
        private String usrTask = null;
        private String pwdTask = null;
        private String phoneTask = null;
        private FormBody formBody = null;
        private Request request = null;
        private Context contxt;
        private UsersInfo user;

        /**
         * 在这个构造方法用于传参数，防止变量域使用错误,传送两个时登录
         *
         * @param username
         * @param password
         */
        public SessionTask(Context context, String username, String password) {
            usrTask = username;
            pwdTask = password;
            contxt = context;
            formBody = new FormBody.Builder()
                    .add(USERLOGINKEY, username)
                    .add(PWDLOGINKEY, password)
                    .build();
            request = new Request.Builder()
                    .url(LOGINURL)
                    .post(formBody)
                    .build();
        }

        /**
         * 注册时候用这个
         *
         * @param username
         * @param password
         * @param phonenumber
         */
        public SessionTask(Context context, String username, String password, String phonenumber) {
            usrTask = username;
            pwdTask = password;
            phoneTask = phonenumber;
            contxt = context;
            formBody = new FormBody.Builder()
                    .add(USERREGISTERKEY, username)
                    .add(PWDREGISTERKEY, password)
                    .add(PHONEREGISTERKEY, phonenumber)
                    .build();
            request = new Request.Builder()
                    .url(REGISTERURL)
                    .post(formBody)
                    .build();
        }

        /**
         * 后台处理，耗时操作不能在主线程上处理
         *
         * @param voids
         * @return
         */
        @Override
        protected String doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
            try {
                Response response = client.newCall(request).execute();
                //如果成功就执行
                //respone.body().string()只会执行一次，执行后就关闭,将数据返回，交给onPostExecute处理
                if (response.isSuccessful()) {
                    String jsonStr = response.body().string();
                    return jsonStr;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * 这里的参数是doInBackground 执行后返回的参数,
         * 然后获取sessionid后发送一个广播并且直接结束
         *
         * @param s
         */
        @Override
        protected void onPostExecute(String s) {
            try {
                int state = -1;
                String sessionid = "";//传送时 intent不能put null value
                Log.d(TAG, "获取后的json数据：" + s);
                Intent intent = new Intent(GET_A_SESSIONID);
                if (null != s) {
                    JSONObject jsonObject = new JSONObject(s);
                    state = jsonObject.getInt(STATE);
                    if (state == LOGINSUCCESSFUL) {
                        sessionid = jsonObject.getString(SESSIONID);
                        updateLocalUser(usrTask, sessionid);
                    }
                    if (null != phoneTask) {
                        intent.putExtra(PHONENUMBER, phoneTask);
                    }
                    intent.putExtra(STATE, state);
                    intent.putExtra(JSON, s);//将json直接返回，方便操作
                    intent.putExtra(USERNAME, usrTask);
                    intent.putExtra(PASSWORD, pwdTask);
                    intent.putExtra(SESSIONID, sessionid);//如果没有就为 null
                    //更新本地数据库,每次登陆或者获取都更新sessionid，在发送广播之前更新
                    contxt.sendBroadcast(intent);//发送广播
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 更新本地数据库中的sessionid
     *
     * @param username
     * @param sessionid
     */
    public void updateLocalUser(String username, String sessionid) {
        UsersInfo usr = new UsersInfo();
        usr.setSessionid(sessionid);
        usr.updateAll("username = ? and status = 1", username);
    }
}